<template>
    <button id="fullscreenButton" v-show="false" @click="requestFullscreen">全屏</button>
    <div class="game-container" id="game-container">
    </div>
    <div style="display: none;" id="gameAudio">
    </div>
</template>

<script setup lang="ts">
import { useRouter, useRoute } from 'vue-router'
import * as PIXI from 'pixi.js'
import { Manager } from '@/game/manager/Manager.ts'
import axios from 'axios'
import Hlddz from '@/game/model/hlddz'
import { Util, getUserInfo } from '@/Util'
import eventBus from '@/Util/EventBus'
const router = useRouter()
const route = useRoute()

eventBus.on('back-home', () => {
    router.push('/home/gamelist')
})

let userinfo = getUserInfo()
let controller: Manager;
let gameid: string;
onMounted(async () => {
    let app = new PIXI.Application({
        width: window.innerWidth,
        height: window.innerHeight,
        background: '#eee',
        resolution: window.devicePixelRatio || 1,
        antialias: true,
    })
    // document.getElementById('fullscreenButton').click() // 进入全屏模式, 已经做过小屏幕适配，暂时不需要
    gameid = route.query?.gameid as string;
    let container = document.getElementById('game-container')
    container.addEventListener('contextmenu', outcardHandler)
    container?.appendChild(app.view as HTMLCanvasElement) // 把canvas添加到幕布
    await initModel()

    // 这个地方需要获取本地model实例，然后初始化
    controller = new Manager(app, window.innerWidth, window.innerHeight)// 初始化控制器
})

let outcardHandler = (e: any) => {
    e.preventDefault()
    eventBus.emit('outcard')
}

onBeforeUnmount(() => {
    let container = document.getElementById('game-container')
    container.removeEventListener('contextmenu', outcardHandler)
})

let initModel = async () => {
    let username = userinfo.username
    if (!gameid) {
        let { data } = await axios.get('/game/id', { params: { username } })
        gameid = data.data;
    }

    if (gameid) { // 用户在一个游戏房间内，这种情况可能是中途退出
        let { data } = await axios.get('/game/model', {
            params: { gameid, playerName: userinfo.username }
        })
        Hlddz.getInstance(data.data)
    } else { // 用户不在任何一个房间内，发请求新建游戏
        let gameid = Util.getVerificationCode(18)
        let { data } = await axios.get('/game/create', { params: { username, gameid } })
        Hlddz.getInstance(data.data)
    }
}
onBeforeUnmount(() => {
    controller.destoryed()
    Hlddz.destroyInstance() // 每次退出游戏，销毁实例
})

function requestFullscreen() {
    var element = document.documentElement;
    if (element.requestFullscreen) {
        element.requestFullscreen();
    }
}
</script>


<style scoped lang="less">
.game-container {
    position: absolute;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    background-color: #eee;
    z-index: 1000;
}
</style>